import {
  tmInfo,
  tmRecordsItem,
  tmRecordsList,
} from '@/api/product/model/trademarkTypes';
import {
  reqAddTM,
  reqDelTM,
  reqTMList,
  reqUpdateTM,
} from '@/api/product/trademark';
import { DeleteOutlined, EditOutlined, PlusOutlined } from '@ant-design/icons';
import {
  Card,
  Button,
  Table,
  Popconfirm,
  Tooltip,
  Image,
  Modal,
  Form,
  Input,
  Upload,
  UploadProps,
  message,
} from 'antd';
import type { ColumnsType } from 'antd/lib/table';
import { RcFile, UploadFile } from 'antd/lib/upload/interface';
import { useEffect, useState } from 'react';
// 上传图片的格式转换
const getBase64 = (file: RcFile): Promise<string> =>
  new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result as string);
    reader.onerror = (error) => reject(error);
  });

export default function Trademark() {
  // 分页数据
  const [current, setCurrent] = useState(1);
  const [pageSize, setPageSize] = useState(5);
  const [total, setTotal] = useState<number>(2);
  // 新增品牌的数据和方法
  const [logoUrl, setLogoUrl] = useState('');
  const [tmName, setTMName] = useState('');
  // table数据
  const [loading, setLoading] = useState(false); // 标识是否正在加载中
  const [tmList, setTMList] = useState<tmRecordsList>([]); // 分页列表数组
  //表格表头及显示内容的设置
  const columns: ColumnsType<tmRecordsItem> = [
    // 指定每一行的数据对象的类型
    {
      title: '序号',
      dataIndex: 'id',
      render(value, row, index) {
        // console.log('render', value, row, index)
        return index + 1;
      },
      fixed: 'left',
      width: 100, // 宽度
      align: 'center', // 水平居中
    },

    {
      title: '品牌名称',
      dataIndex: 'tmName',
    },
    {
      title: '品牌LOGO',
      dataIndex: 'logoUrl',
      render: (value, row, index) => {
        return (
          <>
            <Image width={100} src={row.logoUrl} />
          </>
        );
      },
    },

    {
      title: '操作',
      render: (value, row, index) => {
        return (
          <>
            {' '}
            {/* 必须要一个根标签 */}
            <Tooltip placement="top" title="修改品牌">
              <Button
                type="primary"
                icon={<EditOutlined />}
                onClick={() => updateTM(row)}
              ></Button>
            </Tooltip>
            <Tooltip placement="top" title="删除品牌">
              <Popconfirm
                title={`确定删除${row.tmName}吗?`}
                okText="确定"
                cancelText="取消"
                onConfirm={() => DelTM(row)}
              >
                <Button
                  type="primary"
                  danger
                  icon={<DeleteOutlined />}
                  className="ml"
                />
              </Popconfirm>
            </Tooltip>
          </>
        );
      },
      fixed: 'right', // 固定在右侧
      width: 120, // 指定宽度
    },
  ];

  // 弹窗的数据和方法 start
  const [form] = Form.useForm();
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [id, setId] = useState<number>();
  // 点击card顶部的添加按钮触发--用来重置表单
  const showModal = () => {
    setIsModalOpen(true);
    // 清空输入框和图片
    setTMName('');
    setFileList([]);
    // 清空表单验证
    form.resetFields();
  };
  // 弹窗点击取消按钮触发
  const handleCancel = () => {
    setIsModalOpen(false);
  };
  // 设置表单初始值
  let initValues = {
    tmName: tmName,
    logoUrl: logoUrl,
  };
  // 弹窗点击确认按钮触发
  const handleOk = () => {
    // 表单验证
    form
      .validateFields()
      .then((values) => {
        //检验成功时；
        form.resetFields();
        form.setFieldsValue(values);
        addOrUpdateTM();
        setIsModalOpen(false);
      })
      .catch((info) => {
        //检验失败时；
        message.error('请输入品牌信息');
      });
  };
  // 获取输入框中的品牌名
  const getTMName = (event: any) => {
    // console.log(event.target.value, 'event');
    let tmName = event.target.value;
    setTMName(tmName);
    // console.log(tmName,'tmName');
  };
  // 弹窗的数据和方法 end

  //  图片上传相关数据和方法 start
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  // upload查看大图的功能
  const handlePreview = async (file: UploadFile) => {
    message.error('没有查看大图的功能，懒得整了');
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj as RcFile);
    }
  };
  // upload发生改变触发
  const handleChange: UploadProps['onChange'] = ({ fileList: newFileList }) => {
    // console.log(newFileList, 'newFileList');

    setFileList(newFileList);
    // console.log(newFileList[0]?.response?.data, '上传图片后返回的图片地址');
    // let logoUrl = newFileList[0].response?.data;
    // 获取图片地址
    setLogoUrl(newFileList[0]?.response?.data);
  };
  // 上传图片upload的样式
  const uploadButton = (
    <div>
      <PlusOutlined />
      <div style={{ marginTop: 8 }}>Upload</div>
    </div>
  );
  //  图片上传相关数据和方法 end

  // 获取品牌数据
  const getTMList = async (page = current, limit = pageSize) => {
    // console.log('getTMList', page, limit);
    // 更新当前页码和每页数量
    setCurrent(page);
    setPageSize(limit);
    // 显示loading
    setLoading(true);

    const { records, total } = await reqTMList(page, limit);
    // 隐藏loading
    setLoading(false);
    // 更新状态
    setTMList(records);
    setTotal(total);
  };

  // 初始化请求获取品牌分页列表
  useEffect(() => {
    getTMList(); // 不传递参数
  }, []);

  // 新增品牌
  const addOrUpdateTM = async () => {
    // console.log(id, 'id');

    try {
      if (id) {
        const tmInfo = {
          id: id,
          tmName: tmName,
          logoUrl: logoUrl,
        };
        await reqUpdateTM(tmInfo);
        message.success('修改品牌成功');
      } else {
        await reqAddTM({ tmName, logoUrl });
        message.success('删除品牌成功');
      }
      // console.log(tmName, logoUrl, 'tmName,logoUrl');
      // console.log(res);
      // 重新获取品牌列表
      await getTMList();
    } catch (error) {
      alert(error);
    }
  };

  // 修改品牌的数据回填
  const updateTM = (row: tmInfo) => {
    // console.log(row, 'row');
    setIsModalOpen(true);
    form.setFieldsValue({
      ...row,
    });
    const file = {
      uid: String(row.id),
      name: row.tmName,
      type: 'image/png',
      url: row.logoUrl,
    };
    const photo = [
      {
        uid: String(row.id),
        name: row.tmName,
        type: 'image/png',
        url: row.logoUrl,
      },
    ];
    // console.log(photo, 'photo');
    handleChange({ file: file, fileList: photo });
    // setFileList(photo);
    setId(row.id);
    setTMName(row.tmName);
  };

  // 删除品牌
  const DelTM = async (row: tmInfo) => {
    try {
      // console.log(row.id, 'id');
      await reqDelTM(row.id as number);
      message.success('删除成功');
      getTMList();
    } catch (error) {
      message.error(error + '删除失败');
    }
  };

  return (
    <>
      <Card style={{ margin: 20 }}>
        <div>
          <Button type="primary" icon={<PlusOutlined />} onClick={showModal}>
            添加
          </Button>
        </div>
        <Table
          bordered
          loading={loading}
          dataSource={tmList}
          columns={columns}
          rowKey="id"
          style={{ marginTop: 20 }}
          pagination={{
            current,
            pageSize,
            total,
            pageSizeOptions: [5, 10, 15, 20],
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `总共 ${total} 条`,
            onChange: getTMList,
          }}
        />
      </Card>

      {/* 添加或修改品牌的弹窗 */}
      <Modal
        title={id ? '修改品牌' : '添加品牌'}
        visible={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Form
          name="useForm"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          initialValues={initValues} //初始值设置
          // onFinish={onFinish}
          // onFinishFailed={onFinishFailed}
          // autoComplete="off"
          form={form}
        >
          <Form.Item
            label="品牌名称"
            name="tmName"
            rules={[{ required: true, message: '请输入品牌名称' }]}
          >
            <Input onChange={getTMName} value={tmName} />
          </Form.Item>

          <Form.Item
            label="品牌LOGO"
            name="logUrl"
            rules={[{ required: true, message: '请上传品牌图片' }]}
          >
            <Upload
              action="/dev-proapi/admin/product/upload"
              listType="picture-card"
              fileList={fileList}
              onPreview={handlePreview}
              onChange={handleChange}
            >
              {fileList.length >= 1 ? null : uploadButton}
            </Upload>
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
}
